package com.example.demo1.controller;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: hp
 * Date: 2025-01-09
 * Time: 12:33
 */
@RestController
@RequestMapping("/Header")
public class HeaderController {
    @RequestMapping("/p1")
    public String p1(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if(cookies == null) {
            return "获取Cookie失败";
        }else {
            for(Cookie cookie : cookies) {
                System.out.println(cookie.getName() + ":" + cookie.getValue());
            }
        }
        return "成功获取cookie";
    }

    @RequestMapping("/p2")
    public String p2(@CookieValue("Java") String name) {
        return "从Cookie中获取: " + name;
    }

    @RequestMapping("/p3")
    public String p3(HttpServletRequest request) {
        HttpSession session = request.getSession();//默认true
        session.setAttribute("userName","zhangsan");
        session.setAttribute("age",18);
        return "设置Session成功";
    }

    @RequestMapping("/p4")
    public String p4(HttpServletRequest request) {
        HttpSession session = request.getSession();
        if(session == null && session.getAttribute("userName") == null && session.getAttribute("age") == null) {
            return "获取Session失败";
        }
        String userName = (String) session.getAttribute("userName");
        Integer age = (Integer) session.getAttribute("age");

        return "获取Session成功：userName: " + userName + " " + " age: " + age;
    }


    @RequestMapping("/p5")
    public String p5(HttpSession session) {
        if(session == null && session.getAttribute("userName") == null && session.getAttribute("age") == null) {
            return "获取Session失败";
        }
        String userName = (String) session.getAttribute("userName");
        Integer age = (Integer) session.getAttribute("age");

        return "获取Session成功：userName: " + userName + " " + " age: " + age;
    }

    @RequestMapping("/p6")
    public String p6(@SessionAttribute("userName") String name) {
        return "获取Session成功：userName: " + name;
    }

    @RequestMapping("/p7")
    public String p7(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        return "userAgent: " + userAgent;
    }

    @RequestMapping("/p8")
    public String p8(@RequestHeader("User-Agent") String userAgent) {
        return "userAgent: " + userAgent;
    }
}
